package com.qf.tenant.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.qf.config.AliYunConfig;
import com.qf.tenant.service.SMSCodeService;
import com.qf.vo.R;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class SMSCodeServiceImpl implements SMSCodeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public R SmsVerification(String phone) {

        String s = stringRedisTemplate.boundValueOps("code_" + phone).get();
        if (s!=null&&!"".equals(s)) {
            return new R(true,201,"验证码已发",s);
        }else {
            try {
                String code = getMsgCode();
                AliYunConfig.sendSms(phone, code);
                stringRedisTemplate.boundValueOps("code_"+phone).set(code);
                stringRedisTemplate.boundValueOps("code_"+phone).expire(3, TimeUnit.MINUTES);
                return R.ok(code, "验证码发送成功");
            } catch (ClientException e) {
                return R.fail("验证码发送失败");
            }
        }
    }

    private static String getMsgCode() {
        int n = 6;
        StringBuilder code = new StringBuilder();
        Random ran = new Random();
        for (int i = 0; i < n; i++) {
            code.append(Integer.valueOf(ran.nextInt(10)).toString());
        }
        return code.toString();
    }
}
